/* $Id: LocationInfoPanel.java,v 1.3 2005/04/23 19:01:20 keilw Exp $
 * 
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
 * Microsystems, Inc. All Rights Reserved.
 */


package org.medbeans.modules.search;


import java.beans.PropertyVetoException;
import java.util.Enumeration;
import java.util.StringTokenizer;
//import javax.swing.border.TitledBorder;
import javax.swing.JPanel;

import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerPanel;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileStateInvalidException;
import org.openide.filesystems.FileSystem;
import org.openide.loaders.DataObject;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.TopManager;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;


/**
 *
 * @author  Peter Zavadsky
 */
public class LocationInfoPanel extends JPanel {

    private FileSystem fileSystem = null;
    private String path = null;
    private Node selectedNode = null;
    private DataObject selectedDO = null;
    
    
    /** Creates new form LocationInfoPanel */
    public LocationInfoPanel() {
        initComponents();
        initAccessibility();
        
        resultLabel.setText(NbBundle.getBundle(LocationInfoPanel.class).getString("TEXT_LABEL_LOCATION"));
        fileSystemLabel.setText(NbBundle.getBundle(LocationInfoPanel.class).getString("TEXT_LABEL_FILESYSTEM"));
        pathLabel.setText(NbBundle.getBundle(LocationInfoPanel.class).getString("TEXT_LABEL_PATH"));
        showButton.setText(NbBundle.getBundle(LocationInfoPanel.class).getString("TEXT_BUTTON_SHOW"));
        showButton.setMnemonic(NbBundle.getBundle(LocationInfoPanel.class).getString("TEXT_BUTTON_SHOW_MNEM").charAt(0));
    }
    
    private void initAccessibility() {
        fileSystemNameLabel.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(LocationInfoPanel.class).getString("ACS_FileSystemName"));
        packageNameLabel.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(LocationInfoPanel.class).getString("ACS_PackageName"));
        showButton.getAccessibleContext().setAccessibleDescription(NbBundle.getBundle(LocationInfoPanel.class).getString("ACS_TEXT_BUTTON_SHOW"));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
        java.awt.GridBagConstraints gridBagConstraints;

        resultLabel = new javax.swing.JLabel();
        fileSystemLabel = new javax.swing.JLabel();
        pathLabel = new javax.swing.JLabel();
        showButton = new javax.swing.JButton();
        fileSystemNameLabel = new javax.swing.JTextField();
        packageNameLabel = new javax.swing.JTextField();

        setLayout(new java.awt.GridBagLayout());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        add(resultLabel, gridBagConstraints);

        fileSystemLabel.setLabelFor(fileSystemNameLabel);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
        add(fileSystemLabel, gridBagConstraints);

        pathLabel.setLabelFor(packageNameLabel);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 0, 0, 0);
        add(pathLabel, gridBagConstraints);

        showButton.setText("jButton1");
        showButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showButtonActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(17, 0, 0, 0);
        add(showButton, gridBagConstraints);

        fileSystemNameLabel.setEditable(false);
        fileSystemNameLabel.selectAll();
        fileSystemNameLabel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                fileSystemNameLabelFocusGained(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(11, 11, 0, 0);
        add(fileSystemNameLabel, gridBagConstraints);

        packageNameLabel.setEditable(false);
        packageNameLabel.selectAll();
        packageNameLabel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                packageNameLabelFocusGained(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(11, 11, 0, 0);
        add(packageNameLabel, gridBagConstraints);

    }//GEN-END:initComponents

    private void packageNameLabelFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_packageNameLabelFocusGained
        packageNameLabel.selectAll();
    }//GEN-LAST:event_packageNameLabelFocusGained

    private void fileSystemNameLabelFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fileSystemNameLabelFocusGained
        fileSystemNameLabel.selectAll();
    }//GEN-LAST:event_fileSystemNameLabelFocusGained

    private void showButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showButtonActionPerformed
        showInExplorer();
    }//GEN-LAST:event_showButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel pathLabel;
    private javax.swing.JLabel fileSystemLabel;
    private javax.swing.JTextField fileSystemNameLabel;
    private javax.swing.JButton showButton;
    private javax.swing.JTextField packageNameLabel;
    private javax.swing.JLabel resultLabel;
    // End of variables declaration//GEN-END:variables

    /** Shows info for node. */
    public void showInfo(Node node) {
        String fsName = ""; // NOI18N
        String pkgName = ""; // NOI18N

        // find out filesystem and package of the node
        if (node != null) {
            selectedNode = node;
            fileSystem = null;

            selectedDO = (DataObject) node.getCookie(DataObject.class);
            if (selectedDO != null) {
                FileObject folder = selectedDO.getPrimaryFile().getParent();
                if (folder != null) {
                    try {
                        fileSystem = folder.getFileSystem();
                        fsName = fileSystem.getDisplayName();
                        pkgName = folder.getPackageName('/') + "/"; // NOI18N
                        path = pkgName;
                    } catch (FileStateInvalidException ex) {
                        // filesystem can't be discovered
                        fsName = NbBundle.getBundle(LocationInfoPanel.class).getString("TEXT_NO_FILESYSTEM");
                    }
                }

                resultLabel.setVisible(true);
                fileSystemLabel.setVisible(true);
                pathLabel.setVisible(true);
                showButton.setVisible(true);
                showButton.setEnabled(true);

            }
        } else {
            selectedNode = null;
            fileSystem = null;

            showButton.setEnabled(false);
        }

        fileSystemNameLabel.setText(fsName);
        packageNameLabel.setText(pkgName);
    }

    /** Shows in explorer. */
    private void showInExplorer() {
        if(fileSystem == null || selectedNode == null || selectedDO == null)
            return;

        // get all TopComponents and find main explorer panel (it's not very nice, I know...)
        Object[] comps = TopComponent.getRegistry().getOpened().toArray();
        boolean foundAndSelected = false;

        for (int i=0; i  < comps.length; i++) {
            if (comps[i] instanceof ExplorerPanel) {
                ExplorerPanel ep = (ExplorerPanel)comps[i];
                ExplorerManager em;
                Node rootContext;
                if ((em = ep.getExplorerManager()) != null
                && (rootContext = em.getRootContext()) != null) {
                    if ("Filesystems".equals(rootContext.getName())) { // NOI18N
                        // Now find the node in repository hierarchy...
                        // Node obtained from DataObject can't be used because
                        // it is not in the hieararchy (there is a FilterNode
                        // instead which points to this node).
                        Node node = findNodeInRepository();
                        if (node != null) {
                            try { // try to expand tree and select the node
                                em.setSelectedNodes(new Node[] { node } );
                                ep.open();
                                ep.requestFocus();
                                foundAndSelected = true;
                            }
                            catch (PropertyVetoException ex) {
                            }
                        }
                        break;
                    }
                }
            }
        }

        if (!foundAndSelected) showButton.setEnabled(false);
    }

    /** Finds in repository. */
    private Node findNodeInRepository() {
        Node rootNode = TopManager.getDefault().getPlaces().nodes().repository(),
        node = null;
        Node[] nodes = rootNode.getChildren().getNodes();
        String filesysName = fileSystem.getDisplayName(),
        folder;

        // look for the filesystem node with the same display name
        for (int i=0; i < nodes.length; i++) {
            if (nodes[i].getDisplayName().equals(filesysName)) {
                node = nodes[i];
                break;
            }
        }

        if (path != null && !path.equals("")) { // NOI18N
            StringTokenizer pathItems = new StringTokenizer(path,"/"); // NOI18N

            while (node != null && pathItems.hasMoreTokens()) {
                node = node.getChildren().findChild(pathItems.nextToken());
            }
        }

        if (node == null) return null;

        String nodeName = selectedNode.getName();
        Children ch = node.getChildren();
        node = ch.findChild(nodeName);
        if (node == null) return null;

        Enumeration e = null;
        do {
            DataObject dobj = (DataObject) node.getCookie(DataObject.class);
            if (dobj != null && dobj == selectedDO)
                return node; // this is the right node in repository

            node = null;
            if (e == null) e = ch.nodes();

            while (e.hasMoreElements()) {
                Node nod = (Node)e.nextElement();
                if (nodeName.equals(nod.getName())) {
                    node = nod;
                    break;
                }
            }
        } while (node != null);

        return null;
    }
    
    
}
